//
//  OneViewController.m
//  music
//
//  Created by LT on 2019/3/6.
//  Copyright © 2019 liu. All rights reserved.
//

#import "OneViewController.h"
#import "DCCycleScrollView.h"//图片录播
#import <AFNetworking.h>
#import <YYWebImage.h>

@interface OneViewController ()<DCCycleScrollViewDelegate>
@property (nonatomic,strong)NSMutableArray *ImageArr;
@property (strong, nonatomic) YYAnimatedImageView *imageView;
@property (strong,nonatomic)DCCycleScrollView *banner;
@end

@implementation OneViewController

- (void)viewDidLoad {
    [self httpGet];
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:self.banner];
}

//点击图片的代理
-(void)cycleScrollView:(DCCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    NSLog(@"我点击了轮播图");
}

-(DCCycleScrollView *)banner{
    if (_banner==nil) {
        NSArray *imageArr = @[@"猫1",
                              @"猫2",
                              @"猫3",
                              @"猫4",
                              ];
        _banner = [DCCycleScrollView cycleScrollViewWithFrame:CGRectMake(0,0, self.view.frame.size.width, self.view.frame.size.height*0.4) shouldInfiniteLoop:YES imageGroups:imageArr];
        //banner.placeholderImage = [UIImage imageNamed:@"猫1"];设置滚动视图的背景
        //banner.cellPlaceholderImage = [UIImage imageNamed:@"猫1"];
        _banner.autoScrollTimeInterval = 3.6;
        _banner.autoScroll = YES;
        _banner.isZoom = YES;
        _banner.itemSpace = 0;
        _banner.imgCornerRadius = 10;
        _banner.itemWidth = self.view.frame.size.width - 120;
        _banner.delegate = self;
    }
    return _banner;
}


-(void)httpGet{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    NSDictionary *dict = @{
//                           @"username":@"jyq",
//                           @"pwd":@"jyq",
//                           @"type":@"JSON"
//                           };
    //第一个参数:请求路径(NSString) (URL地址后面无需添加参数)
    //第二个参数:要发送给服务器的参数 (传NSDictionary)
    //第三个参数:progress 进度回调
    //第四个参数:success 成功的回调
//responseObject:响应体(内部默认已经做了JSON的反序列处理)
//    task.response:响应头信息
    //第五个参数:failure 失败的回调
    manager.responseSerializer=[AFJSONResponseSerializer serializer];
    [manager POST:@"https://api.douban.com/v2/movie/in_theaters?count=20" parameters:nil progress:nil success:
     ^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         
         NSDictionary *dict=responseObject;
         //NSLog(@"%@",dict);
         NSArray *videoArr =[[NSArray alloc]initWithArray:dict[@"subjects"]];
         
         //图片的获取
         self.ImageArr = [[NSMutableArray alloc]init];
         for (int i = 0; i < [videoArr count]; i++) {
             NSDictionary *dict = [[NSDictionary alloc]init];
             dict = videoArr[i];
             NSDictionary *imgDict = dict[@"images"];
             if(imgDict[@"large"] != NULL){
                 [self.ImageArr addObject:imgDict[@"large"]];
             }
         }
         NSLog(@"%@",self.ImageArr);
         
         //电影名称的获取
         NSMutableArray *NameArr=[[NSMutableArray alloc]init];
         for (int i=0; i<videoArr.count; i++) {
             NSDictionary *dict=[[NSDictionary alloc]init];
              dict = videoArr[i];
             NSDictionary *nameDict = dict[@"title"];
             [NameArr addObject:nameDict];
         }
         
         NSLog(@"%@",NameArr);
         [self download];
         
         
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         
         NSLog(@"请求失败--%@",error);
     }];

}


-(void)download
{
    //1.创建一个管理者
    AFHTTPSessionManager *manage  = [AFHTTPSessionManager manager];
    
    //2.下载文件
    /*
     第一个参数：请求对象
     第二个参数：下载进度
     第三个参数：block回调，需要返回一个url地址，用来告诉AFN下载文件的目标地址
     targetPath：AFN内部下载文件存储的地址，tmp文件夹下
     response：请求的响应头
     返回值：文件应该剪切到什么地方
     第四个参数：block回调，当文件下载完成之后调用
     response：响应头
     filePath：文件存储在沙盒的地址 == 第三个参数中block的返回值
     error：错误信息
     */
    
    //2.1 创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.ImageArr[0]]];
    NSLog(@"%@",request);
    
    //2.2 创建下载进度，并监听
    NSProgress *progress = nil;
    
    NSURLSessionDownloadTask *downloadTask = [manage downloadTaskWithRequest:request progress:nil destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        
        //拼接文件全路径
        NSString *fullpath = [caches stringByAppendingPathComponent:response.suggestedFilename];
        NSURL *filePathUrl = [NSURL fileURLWithPath:fullpath];
        return filePathUrl;
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nonnull filePath, NSError * _Nonnull error) {
        
        NSLog(@"文件下载完毕---%@",filePath);
    }];
    
    //2.3 使用KVO监听下载进度
    [progress addObserver:self forKeyPath:@"completedUnitCount" options:NSKeyValueObservingOptionNew context:nil];
    
    //3.启动任务
    [downloadTask resume];
}

//获取并计算当前文件的下载进度
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(NSProgress *)progress change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    NSLog(@"%lld--%lld--%f",progress.completedUnitCount,progress.totalUnitCount,1.0 * progress.completedUnitCount/progress.totalUnitCount);
}



//YYWebImage  图片的加载方式
- (void)loadImageAndHandle {
    
    self.imageView=[[YYAnimatedImageView alloc]init];
    self.imageView.frame=CGRectMake(0, 0, 100, 100);
    self.imageView.backgroundColor=[UIColor redColor];
    [self.view addSubview:self.imageView];
    self.view.backgroundColor=[UIColor whiteColor];
    
    NSURL *URL = [NSURL URLWithString:self.ImageArr[0]];
    
    [self.imageView yy_setImageWithURL:URL placeholder:nil options:YYWebImageOptionSetImageWithFadeAnimation progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        
        // 计算进度
        float progress = (float)receivedSize/expectedSize;
        NSLog(@"打印下载进度%f",progress);
        
    } transform:^UIImage * _Nullable(UIImage * _Nonnull image, NSURL * _Nonnull url) {
        
        // 可以额外处理图片在返回 : 截取中心点周围100x100的范围
        //        return [image yy_imageByResizeToSize:CGSizeMake(100, 100) contentMode:UIViewContentModeCenter];
        
        // 返回原始图片
        return image;
        
    } completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
        
        // 测试 : 是否是从磁盘加载的
        if (from == YYWebImageFromDiskCache) {
            NSLog(@"磁盘缓存加载");
        }
    }];
}




@end
